﻿using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CalculateTexMd5 : MonoBehaviour
{
    private RawImage img1;
    private Text md51;

    private RawImage img2;
    private Text md52;

    private RawImage img3;
    private Text md53;

    void Start ()
    {
        this.img1 = this.transform.GetChild(0).GetComponent<RawImage>();
        this.md51 = this.img1.transform.GetChild(0).GetComponent<Text>();

        this.img2 = this.transform.GetChild(1).GetComponent<RawImage>();
        this.md52 = this.img2.transform.GetChild(0).GetComponent<Text>();

        this.img3 = this.transform.GetChild(2).GetComponent<RawImage>();
        this.md53 = this.img3.transform.GetChild(0).GetComponent<Text>();

        this.InitImageTex();
    }

    private void InitImageTex()
    {
        this.img1.texture = Resources.Load<Texture2D>("Texture/One");
        this.img2.texture = Resources.Load<Texture2D>("Texture/Two");
        this.img3.texture = Resources.Load<Texture2D>("Texture/Three");

        this.md51.text = this.CaculateMd5(this.img1.texture as Texture2D);
        this.md52.text = this.CaculateMd5(this.img2.texture as Texture2D);
        this.md53.text = this.CaculateMd5(this.img3.texture as Texture2D);
    }

    private string CaculateMd5(Texture2D texture)
    {
        //在转换成bytes
        byte[] photoByte = texture.EncodeToPNG();
        var md5 = MD5.Create();
        byte[] hash = md5.ComputeHash(photoByte);

        // step 2, convert byte array to hex string
        var sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }
}
